package com.renrenyou.duanshipin.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.renrenyou.duanshipin.R;
import com.renrenyou.duanshipin.about.AboutActivity;
import com.renrenyou.duanshipin.about.FeedBackActivity;
import com.renrenyou.duanshipin.about.WebActivity;
import com.renrenyou.duanshipin.base.BaseFragment;
import com.renrenyou.duanshipin.bean.UserInfoData;
import com.renrenyou.duanshipin.databinding.FragmentMeBinding;
import com.renrenyou.duanshipin.login.LoginActivity;
import com.renrenyou.duanshipin.net.Constance;
import com.renrenyou.duanshipin.net.MyOkhttp;
import com.renrenyou.duanshipin.net.MyOkhttpCallback;
import com.renrenyou.duanshipin.util.ActivityUtil;
import com.renrenyou.duanshipin.util.NetUtil;
import com.renrenyou.duanshipin.util.ProgressDialogUtil;
import com.renrenyou.duanshipin.util.SharedPref;
import com.renrenyou.duanshipin.util.ToastUtil;

import java.lang.ref.WeakReference;
import java.security.SecureRandom;

import okhttp3.Call;

public class MeFragment extends BaseFragment<FragmentMeBinding> implements View.OnClickListener {

    private Call mCall;
    private int[] mAvatars = new int[]{R.mipmap.ic_avatar1, R.mipmap.ic_avatar2, R.mipmap.ic_avatar3,
            R.mipmap.ic_avatar4, R.mipmap.ic_avatar5, R.mipmap.ic_avatar6,
            R.mipmap.ic_avatar7, R.mipmap.ic_avatar8, R.mipmap.ic_avatar9};

    @Override
    public FragmentMeBinding getBinding(LayoutInflater inflater) {
        return FragmentMeBinding.inflate(inflater);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Glide.with(this).load(R.mipmap.ic_material_bg).into(mBinding.ivMeBg);

        mBinding.vMeBg1.setOnClickListener(this);
        mBinding.vMeYinsi.setOnClickListener(this);
        mBinding.vMeXieyi.setOnClickListener(this);
        mBinding.vMeAbout.setOnClickListener(this);
        mBinding.vMeUnregister.setOnClickListener(this);
        mBinding.vMeLogout.setOnClickListener(this);
        mBinding.vMeFeedBack.setOnClickListener(this);

        String phone = SharedPref.getInstance().getString("phone", null);
        if (TextUtils.isEmpty(phone)) {
            mBinding.tvMeLogin.setText("前往登录");
            loadAvatar(false);
        } else {
            showPhone(phone);
            loadAvatar(true);
        }

        mRecevier = new Myreceiver(mBinding.tvMeLogin);

        IntentFilter filter = new IntentFilter();
        filter.addAction("loginSuc");
        ContextCompat.registerReceiver(getContext(), mRecevier, filter, ContextCompat.RECEIVER_NOT_EXPORTED);
    }

    private void loadAvatar(boolean isLogin) {
        SecureRandom random = new SecureRandom();
        Glide.with(this).load(isLogin ? mAvatars[random.nextInt(mAvatars.length - 1)] : "")
                .apply(new RequestOptions()
                        .placeholder(R.drawable.me_avatar)
                        .circleCrop())
                .into(mBinding.ivMeAvatar);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.v_me_bg1) {
            //前往登录
            if (!Constance.isLogin) {
                ActivityUtil.startActivity(getContext(), LoginActivity.class);
            } else {
                ToastUtil.showToast(getContext(), "您已登录，无须重复登录");
            }
        } else if (view.getId() == R.id.v_me_yinsi) {
            //隐私
            Intent intent = new Intent(getContext(), WebActivity.class);
            intent.putExtra("title", "隐私政策");
            intent.putExtra("url", Constance.YINSI);
            startActivity(intent);
        } else if (view.getId() == R.id.v_me_xieyi) {
            //协议
            Intent intent = new Intent(getContext(), WebActivity.class);
            intent.putExtra("title", "用户协议");
            intent.putExtra("url", Constance.XIEYI);
            startActivity(intent);
        } else if (view.getId() == R.id.v_me_about) {
            //关于我们
            ActivityUtil.startActivity(getContext(), AboutActivity.class);
        } else if (view.getId() == R.id.v_me_unregister) {
            logout(1);
        } else if (view.getId() == R.id.v_me_logout) {
            logout(2);
        } else if (view.getId() == R.id.v_me_feed_back) {
            ActivityUtil.startActivity(getContext(), FeedBackActivity.class);
        }
    }

    private void logout(int flag) {
        AlertDialog dialog = ProgressDialogUtil.showProgressDialog(getContext());
        Handler handler = new Handler();
        handler.postDelayed(() -> {
            dialog.dismiss();
            NetUtil.logout();
            mBinding.tvMeLogin.setText("前往登录");
            loadAvatar(false);
            ToastUtil.showToast(getContext(), flag == 1 ? "已注销" : "已退出");
        }, 1500);
    }

    private void loadUserInfo() {
        mCall = MyOkhttp.getInstance().get(Constance.BASE_URL + Constance.USER_INFO, Constance.TOKEN,
                new MyOkhttpCallback<UserInfoData>() {
                    @Override
                    public void onFailed(int errorCode, int errorMsg) {
                        ToastUtil.showToast(getContext(), getString(errorMsg));
                    }

                    @Override
                    public void onSuccess(UserInfoData userInfoData) {
                        if (userInfoData != null) {
                            if (userInfoData.isSuccess()) {
                                UserInfoData.UserInfo userInfo = userInfoData.getData();
                                if (userInfo != null) {
                                    showPhone(userInfo.getPhone());
                                }
                            } else {
                                ToastUtil.showToast(getContext(), userInfoData.getMessage());
                                NetUtil.error(userInfoData.getCode());
                                if (userInfoData.getCode() == 401) {
                                    mBinding.tvMeLogin.setText("前往登录");
                                }
                            }
                        }
                    }
                });
    }

    private Myreceiver mRecevier;

    private class Myreceiver extends BroadcastReceiver {
        private WeakReference<TextView> mPhoneNumber;

        public Myreceiver(TextView phoneNumber) {
            mPhoneNumber = new WeakReference<>(phoneNumber);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if ("loginSuc".equals(intent.getAction())) {
                TextView phoneText = mPhoneNumber.get();
                if (phoneText != null) {
                    showPhone(phoneText, intent.getStringExtra("phone"));
                }
                loadAvatar(true);
            } else if ("loginOut".equals(intent.getAction())) {
                TextView phoneText = mPhoneNumber.get();
                if (phoneText != null) {
                    phoneText.setText("前往登录");
                }
                loadAvatar(false);
            }
        }

        private void showPhone(TextView textView, String phone) {
            if (!TextUtils.isEmpty(phone) && phone.length() >= 3) {
                textView.setText(phone.substring(0, 2) + "********" + phone.substring(phone.length() - 1, phone.length()));
            } else {
                textView.setText(phone);
            }
        }
    }

    private void showPhone(String phone) {
        if (!TextUtils.isEmpty(phone) && phone.length() >= 3) {
            mBinding.tvMeLogin.setText(phone.substring(0, 2) + "********" + phone.substring(phone.length() - 1, phone.length()));
        }
    }

    @Override
    public void onDestroyView() {
        if (mCall != null) {
            mCall.cancel();
        }
        if (mRecevier != null && getContext() != null) {
            getContext().unregisterReceiver(mRecevier);
        }
        super.onDestroyView();
    }
}
